package com.pigotech.ptwo.socket;

/**
 * Created by ghb on 2018/3/20.
 */

import android.util.Log;

import com.pigotech.ptwo.entity.NormalVideo;
import com.pigotech.ptwo.interfaces.CallBack;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

public class CommandSocket {
    private static CommandSocket instance;
    public String ip = "192.168.42.1";  // socket命令IP
    private int port = 7878;   // socket命令端口
    public String tokenNum = "";  //tokenNum
    public String video_list_json = ""; //最后拼接完成的json完整数据
    public ChannelFuture future = null;
    final ClientBootstrap bootstrap;
    private List<NormalVideo> normalVideos ;

    boolean isTakePhoto = true;

    public static CommandSocket getInstance() {
        if (instance == null)
            instance = new CommandSocket();
        return instance;
    }

    public void disConnect() {
        if (null != future && null != future.getChannel() && future.getChannel().isOpen()
                && future.getChannel().isConnected()) {
            future.getChannel().unbind();
            future.getChannel().close();
        }
    }

    /**
     * 连接socket
     */
    public void connect() {
        if (null != future && null != future.getChannel()
                && future.getChannel().isOpen()
                && future.getChannel().isConnected()) {
            future.getChannel().unbind();
            future.getChannel().close();
        }

        new Thread() {
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.d("GHB", "channelConnecting...");
                future = bootstrap.connect(new InetSocketAddress(ip, port));

            }
        }.start();
    }

    public CommandSocket() {
        bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool()));
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("decoder", new StringDecoder());
                pipeline.addLast("encoder", new StringEncoder());
                pipeline.addLast("handler", new CommandChannelHandler());
                return pipeline;
            }
        });

    }

    /**
     * 调用startSession
     */
    class CommandChannelHandler extends SimpleChannelHandler {

        @Override
        public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
            super.channelClosed(ctx, e);
            Log.d("GHB", "channelClosed");
        }

        @Override
        public void channelConnected(ChannelHandlerContext ctx,
                                     ChannelStateEvent e) throws Exception {
            Log.d("GHB", "channelConnected");
//            if (future != null && future.getChannel() != null) {
//                future.getChannel().write("{\"msg_id\":257,\"token\":0}");
//            }

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    future.getChannel().write("{\"msg_id\":257,\"token\":0}");
                }
            }).start();

            super.channelConnected(ctx, e);
        }

        /**
         * 接收json
         * @param ctx
         * @param e
         */
        public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
            String message = (String) e.getMessage();
            String msg_id = "";
            String param = "";
            JSONObject jsonObject = null;
            Log.d("GHB", "MCommandChannelHandleressage" + message);

            try {
                jsonObject = new JSONObject(message);
                msg_id = jsonObject.getString("msg_id");
                if (msg_id.equals("257")){
                    param = jsonObject.getString("param");
                    tokenNum = param;
                }
            } catch (JSONException e1) {
//                e1.printStackTrace();
            }
            if (msg_id.equals("257")) {
                tokenNum = param;
            }

            if (message.endsWith("}")){
                video_list_json = video_list_json + message;
                jsonOperation(video_list_json);
            } else {
                video_list_json = video_list_json + message;
            }
//            if (msg_id.equals("769")) {
//                Log.d("GHB", "TakePhoto" + message);
//            }
//            if (msg_id.equals("268435458")) {
//
//            }
//            if(video_list_json.contains("268435458") && video_list_json.contains("Amount") && video_list_json.contains("TotalSize")) {
//                //normal视频列表数据包拼接完成后进行解析
//                JSONObject video_list_jsonObject = null;
//                JSONArray video_list_jsonArray = null;
//                String listing = "";
//                try {
//                    video_list_jsonObject = new JSONObject(video_list_json);
//                    video_list_jsonArray = video_list_jsonObject.getJSONArray("listing");
//
//                } catch (JSONException e1) {
//                    e1.printStackTrace();
//                }
//
//            }

        }
    }

    /**
     * 对返回的json字符串进行处理
     * @param jsonStr
     */
    public void jsonOperation(String jsonStr) {
        String msg_id = "";
        String param = "";
        String rval = "";//返回数据如果是0表示成功
//        ArrayList jsonArray = new ArrayList();
        if(jsonStr.contains("}{")) {
            jsonStr = jsonStr.replaceAll("\\}\\{", "\\}ImSeparator\\{");
            Log.d("GHB", "jsonArray String =" + jsonStr);
            String jsonArray [] = jsonStr.split("ImSeparator");
            JSONObject [] jsonObject = null;
            for (int i = 0; i < jsonArray.length; i ++) {
                Log.d("GHB", "jsonArray []" + i + "=" + jsonArray[i].toString());
//                try {
//                    jsonObject[i] = new JSONObject(jsonArray[i]);
//                    if(msg_id.equals("268435458")) {
//                        Log.d("GHB", "视频列表" + i + "=" + jsonArray[i].toString());
//                    }
//
//                } catch (JSONException e) {
////                    e.printStackTrace();
//                }

            }
        } else {
            Log.d("GHB", "jsonArray String else  =" + jsonStr);
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(jsonStr);
                msg_id = jsonObject.getString("msg_id");
                if (msg_id.equals("257")){
                    param = jsonObject.getString("param");
                    tokenNum = param;
                }
            } catch (JSONException e1) {
//                e1.printStackTrace();
            }
            if(msg_id.equals("769")) {
                Log.d("GHB", "TakePhoto" + jsonStr);
            }
            if(msg_id.equals("268435458")) {
                normalVideos = new ArrayList<>();
                Log.d("GHB", "视频列表json" + jsonStr);
                try {
                    JSONObject jsonObject_normal_videos = new JSONObject(jsonStr);
                    JSONArray jsonArray = jsonObject_normal_videos.optJSONArray("listing");
                    if (null != jsonArray) {
                        for (int i = 0; i < jsonArray.length(); i ++) {
                            JSONObject jsonObject_normal_video = jsonArray.getJSONObject(i);
                            NormalVideo normalVideo = new NormalVideo(jsonObject_normal_video);
                            normalVideos.add(normalVideo);
                        }
                    }
//                    mOnCallBackListener.onCallBackListener(normalVideos);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 拍照
     */
    public void takePhoto() {
        if (future != null && future.getChannel() != null) {
            future.getChannel().write("{\"msg_id\":769,\"token\":" + tokenNum + "}");
            Log.d("GHB", "拍照" + tokenNum);
        }
    }

    /**
     * 获取DVR普通视频列表
     */
    public void getNormalVideo() {
        video_list_json = "";
        if (future != null && future.getChannel() != null) {
            future.getChannel().write("{\"msg_id\":268435458,\"token\":" + tokenNum +  ",\"type\":\"normal\"}");
//            future.getChannel().write("{\"msg_id\":1282,\"token\":" + tokenNum +  ",\"type\":\"normal\"}");
            Log.d("GHB", "获取DVR普通视频列表" + tokenNum);
        }
    }

    public CallBack mCallBack;

    public void setCallBack(CallBack callBack) {
        mCallBack = callBack;
    }

    public void doCallBackMethod() {
        mCallBack.doSomething(normalVideos);
    }

}
